//
//  RegisterView.swift
//  SCA
//
//  Created by tjun on 2025/9/2.
//

import UIKit
import TTTAttributedLabel


class RegisterView: UIView {
    
    private let rules: [PasswordRule] = [
        PasswordRule(title: "必须包含字母".localizedString) { $0.range(of: "[A-Za-z]", options: .regularExpression) != nil },
        PasswordRule(title: "必须包含数字".localizedString) { $0.range(of: "[0-9]", options: .regularExpression) != nil },
        PasswordRule(title: "至少8个字符".localizedString) { $0.count >= 8 },
        PasswordRule(title: "必须包含符号".localizedString) { $0.range(of: "[^A-Za-z0-9]", options: .regularExpression) != nil }
    ]
    
    let referralCodeTextField = LabeledTextField(tip: "请输入您的引荐码。".localizedString)
    let usernameTextField = LabeledTextField(tip: "用户名 至少6个字符，必须由字母和数字所组合。".localizedString)
    let passwordTextField = LabeledTextField()
    let confirmPasswordTextField = LabeledTextField(tip: "请重新输入您的密码。".localizedString)
    
    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)
    private lazy var validationView = PasswordValidationView(rules: rules)

    var onAgreementLabeLinkTaped: ((URL) -> Void)?
    var onConfirmButtonTaped: (() -> Void)?

    var lastView: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
  
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reset() {
        referralCodeTextField.textField.text = nil
        usernameTextField.textField.text = nil
        passwordTextField.textField.text = nil
        confirmPasswordTextField.textField.text = nil
        textFieldDidChange(referralCodeTextField.textField)
    }
    
    private func setupUI() {
        
        if isDevelopment() {
            referralCodeTextField.titleAttributedText = "引荐码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        } else {
            referralCodeTextField.title = "引荐码".localizedString
        }
        referralCodeTextField.textField.keyboardType = .asciiCapable
        referralCodeTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        addSubview(referralCodeTextField)
        referralCodeTextField.snp.makeConstraints { make in
            make.top.equalTo(24)
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
        }
        
        usernameTextField.titleAttributedText = "用户名*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        usernameTextField.textField.keyboardType = .asciiCapable
        addSubview(usernameTextField)
        usernameTextField.snp.makeConstraints { make in
            make.top.equalTo(referralCodeTextField.snp.bottom).offset(20)
            make.left.right.equalTo(referralCodeTextField)
        }
        
        passwordTextField.titleAttributedText = "密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        addSubview(passwordTextField)
        passwordTextField.textField.keyboardType = .asciiCapable
        passwordTextField.textField.addTarget(self, action: #selector(passwordChanged(_ :)), for: .editingChanged)
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(usernameTextField.snp.bottom).offset(20)
            make.left.right.equalTo(usernameTextField)
        }
        
        validationView.addTo(self)
        validationView.snp.makeConstraints { make in
            make.top.equalTo(passwordTextField.snp.bottom).offset(6)
            make.left.right.equalTo(usernameTextField)
        }
        
        confirmPasswordTextField.titleAttributedText = "确认密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        confirmPasswordTextField.textField.keyboardType = .asciiCapable
        confirmPasswordTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        addSubview(confirmPasswordTextField)
        confirmPasswordTextField.snp.makeConstraints { make in
            make.top.equalTo(validationView.snp.bottom).offset(20)
            make.left.right.equalTo(usernameTextField)
        }

        let agreementText = "点击‘确认’按钮，视为您已阅读并同意本《服务条款》全部条款".localizedString
        let agreementLabel = TTTAttributedLabel().addTo(self)
        agreementLabel.numberOfLines = 0
        agreementLabel.isUserInteractionEnabled = true
        agreementLabel.snp.makeConstraints { make in
            make.left.right.equalTo(usernameTextField)
            make.centerX.equalToSuperview()
            make.top.equalTo(confirmPasswordTextField.snp.bottom).offset(20)
        }
        
        let attributedText = NSMutableAttributedString(string: agreementText)
        let range = (agreementText as NSString).range(of: "《服务条款》".localizedString)
        
        let fullRange = NSRange(location: 0, length: agreementText.count)
        attributedText.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: fullRange)
        attributedText.addAttribute(.foregroundColor, value: Assets.Color.loginAgreementTitle, range: fullRange)
        attributedText.addAttribute(.foregroundColor, value: Assets.Color.hex00CCFF, range: range)
        agreementLabel.delegate = self
        agreementLabel.linkAttributes = [
            NSAttributedString.Key.foregroundColor: Assets.Color.hex00CCFF,
        ]

        agreementLabel.activeLinkAttributes = [
            NSAttributedString.Key.foregroundColor: Assets.Color.hex00CCFF.withAlphaComponent(0.5)
        ]
        agreementLabel.setText(attributedText)
        
        if let URL = URL(string: "https://www.baidu.com") {
            let range = (agreementText as NSString).range(of: "《服务条款》".localizedString)
            agreementLabel.addLink(to: URL, with: range)
        }
        
        confirmButton.addTo(self)
        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(usernameTextField)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(agreementLabel.snp.bottom).offset(16)
        }
        
        lastView = confirmButton
        
        if AppEnvironment.isDebug {
            referralCodeTextField.textField.text = "LSOEP4ca"
        }
    }
    
    @objc func textFieldDidChange(_ sender: UITextField) {
        
        if isDevelopment() {
            if let referralCode = referralCodeTextField.textField.text,
               let username = usernameTextField.textField.text,
               let password = passwordTextField.textField.text,
               let confirmPassword = confirmPasswordTextField.textField.text,
               referralCode.count > 0,
               isValidUsername(username),
               isValidPassword(password),
               password == confirmPassword {
                confirmButton.isEnabled = true
            } else {
                confirmButton.isEnabled = false
            }
        } else {
            if let username = usernameTextField.textField.text,
               let password = passwordTextField.textField.text,
               let confirmPassword = confirmPasswordTextField.textField.text,
               isValidUsername(username),
               isValidPassword(password),
               password == confirmPassword {
                confirmButton.isEnabled = true
            } else {
                confirmButton.isEnabled = false
            }
        }

    }
    
    @objc private func passwordChanged(_ sender: UITextField) {
        validationView.validate(password: sender.text ?? "")
    }
    
    @objc func confirmButtonTapped() {
        onConfirmButtonTaped?()
    }
}


extension RegisterView: TTTAttributedLabelDelegate {
    func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
        onAgreementLabeLinkTaped?(url)
    }
}
